<!DOCTYPE html>
<html>
    <head>
        <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        <title>Upload to NIHR Hub</title>
        
        <script>
            // Replace with Google API key
            window.APIKey = "AIzaSyApVcaHU-Drez2RpLdOu5AUOZeL6tOq6Lk";
            window.clientID = "456108084199-keqche7lea1kb1f9m8tmfg17pojul8mc.apps.googleusercontent.com";
            
            // Replace with fusion table IDs
            window.recruitmentTableID = "1S5VGpvqa3s5EknoDXTUYt-k2SkuhT7n3BhKJIrKM";
            window.studyInfoTableID = "15Hjojdr2KMMR9P50TABJpU-h-4RwniraR-pOINU9";
        </script>
        
        <style>
            .dropzone {
                height: 100px;
            }
            .dropzone.dropped {
                background-color: white;
            }
            .hidden {
                display: none;
            }
            .well {
                text-align: center;
            }
            .status {
                text-align: right;
            }
            .spacer-top {
                height: 40px;
            }
            .well-offset {
                height: 10px;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="col-xs-2"></div>
            <div class="col-xs-8">
                
                <div class="row spacer-top"></div>
                
                <div class="alert alert-danger hidden" id="alert">
                    Oh no
                </div>
            
                <div class="panel panel-primary">
                    <div class="panel-heading">
                        <strong>Upload to NIHR portal</strong>
                    </div>
                    
                    <div class="panel-body">
                        <h6 id="prompt">
                            Drop .csv files onto wells
                        </h6>
                        <div class="row well-offset"></div>
                        <div class="row">
                            <div class="col-xs-3"></div>
                            <div class="col-xs-4 dropzone well" id="dropRecruitment">
                                <span class="glyphicon glyphicon-file"></span>
                                Q_ActivityMonthly
                            </div>
                            <div class="col-xs-3"></div>
                        </div>
                        
                        <div class="row">
                            <div class="col-xs-12">
                                <button type="button" class="btn btn-primary" id="uploadButton" disabled="disabled">
                                    <span class="glyphicon glyphicon-upload"></span>
                                    Upload
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <script src='//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script>  
        <script src='//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js'></script>
        <script src="//apis.google.com/js/client.js"></script>
        
        <script>
            "use strict";
            
            var gapi = window.gapi;
            var pickedFiles = {};
            
            function setVisible(elementID, visible, callback) {
                var elem = document.getElementById(elementID);
                
                if (visible) {
                    elem.classList.remove("hidden");
                } else {
                    elem.classList.add("hidden");
                }
                
                if (callback) callback(elem);
            }
            
            function alert(text) {
                setVisible("alert", true, function(elem) {
                    elem.innerHTML = text;
                });
            }
            
            function hideAlert() {
                setVisible("alert", false);
            }
            
            function setPrompt(text) {
                document.getElementById("prompt").textContent = text;
            }
        
            function bindFilePicker(elementID, callback) {
                function handleFileSelect(evt) {
                    evt.stopPropagation();
                    evt.preventDefault();
                    
                    var files = evt.dataTransfer.files;
                    
                    if (files.length === 1) {
                        document.getElementById(elementID).classList.add("dropped");
                        
                        var reader = new FileReader();
                        reader.onload = function() {
                            callback(reader.result);
                        };
                        
                        reader.readAsText(files[0]);
                    }
                }
                
                function handleDragOver(evt) {
                    evt.stopPropagation();
                    evt.preventDefault();
                    
                    var files = evt.dataTransfer.items;
                    if (files.length === 1) {
                        evt.dataTransfer.dropEffect = 'copy';
                    } else {
                        evt.dataTransfer.dropEffect = 'none';
                    }
                }
                
                var dropZone = document.getElementById(elementID);
                
                dropZone.addEventListener('dragover', handleDragOver, false);
                dropZone.addEventListener('drop', handleFileSelect, false);
            }
            
            function filePickedHandler(tableID) {
                return function(dataURL) {
                    pickedFiles[tableID] = dataURL;
                    updateUploadButton();
                };
            }
            
            function updateUploadButton() {
                if (pickedFiles[window.recruitmentTableID]) {
                    setPrompt("Ready to upload");
            
                    var uploadButton = document.getElementById("uploadButton");
                    uploadButton.disabled = false;
                    uploadButton.addEventListener('click', uploadClickedHandler);
                }
            }
            
            function replaceTableContent(auth, table) {
                function deleteAll() {
                    return gapi.client.request({
                        path: "fusiontables/v1/query",
                        method: "POST",
                        params: {sql: "DELETE FROM " + table}
                    });
                }
                
                function insert() {
                    return gapi.client.request({
                        path: "upload/fusiontables/v1/tables/" + table + "/import",
                        method: "POST",
                        params: {uploadType: "media", startLine: 1},
                        headers: {"Content-Type": "application/octet-stream"},
                        body: pickedFiles[table]
                    });
                }
                
                return gapi.client.request({
                    path: "fusiontables/v1/query",
                    params: {sql: "SELECT * FROM " + table}
                    
                }).then(function(response){
                    var result = JSON.parse(response.body);
                    
                    if (result.rows.length > 0) {
                        return insert();
                    } else {
                        return deleteAll().then(insert);
                    }
                });
            }
            
            function uploadClickedHandler() {
                hideAlert();
                setPrompt("Uploading...");
                
                authorizeAPICall(function(auth) {
                    Promise.all([
                        replaceTableContent(auth, window.recruitmentTableID)
                    ]).then(
                        function() {
                            setPrompt("Done!");
                        },
                        function(error){
                            console.log(error);
                            var body = JSON.parse(error.body);
                            alert(
                                "<strong>Failed to upload data to hub. </strong>"
                                + body.error.errors[0].message
                            );
                            
                            setPrompt("Ready to upload...");
                        }
                    )
                    .then(undefined, function() {
                        alert(
                            "<strong>Something went wrong. </strong> See console for details"
                        );
                    });
                });
            }
            
            function authorizeAPICall(makeApiCall) {
                function handleAuthResult(authResult) {
                    console.log(authResult);
                    
                    if (authResult && !authResult.error) {
                        makeApiCall(authResult.access_token);
                    } else {
                        throw authResult.error;
                    }
                }
                
                function checkAuth() {
                    gapi.auth.authorize({
                        client_id: window.clientID, 
                        scope: "https://www.googleapis.com/auth/fusiontables", 
                        immediate: false
                    }, handleAuthResult);
                }
                
                gapi.client.setApiKey(window.APIKey);
                window.setTimeout(checkAuth,1);
            }

            bindFilePicker("dropRecruitment", filePickedHandler(window.studyInfoTableID));
            
            setPrompt("Drop .csv files for report onto the wells.");
        </script>
    </body>
</html>
